package view.principal;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.border.TitledBorder;

import model.entidades.Usuario;
import model.repositorio.util.ConexaoBD;

import org.eclipse.wb.swing.FocusTraversalOnArray;

import controller.ControladorExcecao;
import controller.ControladorSessao;
import controller.ControladorUsuario;
import utils.Criptografia;
import view.componentes.PlaceholderPasswordField;
import view.componentes.PlaceholderTextField;

public class TelaLogin extends JFrame implements ActionListener {

	private static final long serialVersionUID = 1L;

	private JPanel contentPane;
	private JPanel panelFundo;
	private JPanel panelFomulario;

	private JLabel ldlLogo;
	private JLabel lblBemVindo;

	private PlaceholderTextField txtLogin;
	private PlaceholderPasswordField txtSenha;

	private JButton btnEntrar;
	private JButton btnCancelar;

	public static void main(String[] args) {

		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
						if ("Nimbus".equals(info.getName())) {
							UIManager.setLookAndFeel(info.getClassName());
							break;
						}else{
							UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
						}
					}
					TelaLogin window = new TelaLogin();
					window.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});		
	}

	public TelaLogin() {
		inicializaComponentes();
	}

	private void inicializaComponentes(){
		setUndecorated(true);
		setResizable(false);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 300, 370);
		setLocationRelativeTo(null);
		contentPane = new JPanel();
		contentPane.setBackground(Color.WHITE);
		contentPane.setBorder(new TitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		setContentPane(contentPane);
		contentPane.setLayout(new BorderLayout(0, 0));

		panelFundo = new JPanel();
		panelFundo.setOpaque(false);
		panelFundo.setBackground(Color.WHITE);
		panelFundo.setBorder(null);
		contentPane.add(panelFundo, BorderLayout.CENTER);

		btnCancelar = new JButton("Cancelar");
		btnCancelar.setActionCommand("Cancel");
		btnCancelar.addActionListener(this);
		btnCancelar.setToolTipText("Clique para sair do sistema.");

		panelFomulario = new JPanel();
		panelFomulario.setOpaque(false);
		panelFomulario.setBorder(null);

		ldlLogo = new JLabel("");
		ldlLogo.setHorizontalAlignment(SwingConstants.CENTER);
		ldlLogo.setIcon(new ImageIcon(TelaLogin.class.getResource("/resources/logo_login.png")));
		GroupLayout gl_panelFundo = new GroupLayout(panelFundo);
		gl_panelFundo.setHorizontalGroup(
				gl_panelFundo.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_panelFundo.createSequentialGroup()
						.addGroup(gl_panelFundo.createParallelGroup(Alignment.LEADING)
								.addGroup(gl_panelFundo.createSequentialGroup()
										.addContainerGap()
										.addComponent(ldlLogo, GroupLayout.DEFAULT_SIZE, 268, Short.MAX_VALUE))
										.addGroup(gl_panelFundo.createSequentialGroup()
												.addContainerGap()
												.addComponent(panelFomulario, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
												.addGroup(gl_panelFundo.createSequentialGroup()
														.addGap(95)
														.addComponent(btnCancelar, GroupLayout.PREFERRED_SIZE, 89, GroupLayout.PREFERRED_SIZE)))
														.addContainerGap())
				);
		gl_panelFundo.setVerticalGroup(
				gl_panelFundo.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_panelFundo.createSequentialGroup()
						.addContainerGap()
						.addComponent(ldlLogo, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
						.addPreferredGap(ComponentPlacement.UNRELATED)
						.addComponent(panelFomulario, GroupLayout.PREFERRED_SIZE, 154, GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(ComponentPlacement.UNRELATED)
						.addComponent(btnCancelar, GroupLayout.PREFERRED_SIZE, 40, GroupLayout.PREFERRED_SIZE)
						.addGap(12))
				);

		txtSenha = new PlaceholderPasswordField();
		txtSenha.setEchoChar('●');
		txtSenha.setFont(new Font("Tahoma", Font.PLAIN, 17));
		txtSenha.setPlaceholder("Senha");
		txtSenha.setToolTipText("Digite sua senha.");
		txtSenha.setColumns(10);

		txtLogin = new PlaceholderTextField();
		txtLogin.setFont(new Font("Tahoma", Font.PLAIN, 17));
		txtLogin.setPlaceholder("Login");
		txtLogin.setToolTipText("Digite seu nome de usu\u00E1rio.");
		txtLogin.setColumns(10);

		btnEntrar = new JButton("Entrar");
		btnEntrar.setActionCommand("OK");
		btnEntrar.addActionListener(this);
		btnEntrar.setForeground(Color.WHITE);
		btnEntrar.setBackground(new Color(30, 144, 255));
		btnEntrar.setFont(new Font("SansSerif", Font.BOLD, 14));
		btnEntrar.setToolTipText("Clique para fazer login no sistema.");

		lblBemVindo = new JLabel("Bem-Vindo!");
		lblBemVindo.setFont(new Font("SansSerif", Font.PLAIN, 14));

		GroupLayout gl_panelFomulario = new GroupLayout(panelFomulario);
		gl_panelFomulario.setHorizontalGroup(
				gl_panelFomulario.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panelFomulario.createSequentialGroup()
						.addGroup(gl_panelFomulario.createParallelGroup(Alignment.LEADING)
								.addGroup(gl_panelFomulario.createSequentialGroup()
										.addGap(18)
										.addGroup(gl_panelFomulario.createParallelGroup(Alignment.LEADING)
												.addComponent(txtSenha, GroupLayout.PREFERRED_SIZE, 233, GroupLayout.PREFERRED_SIZE)
												.addComponent(txtLogin, GroupLayout.PREFERRED_SIZE, 203, GroupLayout.PREFERRED_SIZE)
												.addComponent(btnEntrar, GroupLayout.PREFERRED_SIZE, 233, GroupLayout.PREFERRED_SIZE)))
												.addGroup(gl_panelFomulario.createSequentialGroup()
														.addGap(97)
														.addComponent(lblBemVindo)))
														.addContainerGap(17, Short.MAX_VALUE))
				);
		gl_panelFomulario.setVerticalGroup(
				gl_panelFomulario.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panelFomulario.createSequentialGroup()
						.addContainerGap()
						.addComponent(lblBemVindo)
						.addPreferredGap(ComponentPlacement.RELATED)
						.addComponent(txtLogin, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(ComponentPlacement.RELATED)
						.addComponent(txtSenha, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(ComponentPlacement.RELATED)
						.addComponent(btnEntrar, GroupLayout.DEFAULT_SIZE, 48, Short.MAX_VALUE))
				);
		gl_panelFomulario.linkSize(SwingConstants.HORIZONTAL, new Component[] {txtSenha, txtLogin});
		panelFomulario.setLayout(gl_panelFomulario);
		panelFundo.setLayout(gl_panelFundo);

		setFocusTraversalPolicy(new FocusTraversalOnArray(new Component[]{txtLogin, txtSenha, btnEntrar, btnCancelar}));
	}//inicializaComponentes()

	private void botaoEntrar(){
		ControladorUsuario controladorUsuario = new ControladorUsuario(null);
		try {
			Usuario usuario = controladorUsuario.pesquisarUsuarioLogin(txtLogin.getText());
			if(usuario.getSenha().equals(Criptografia.criptografaSenha(new String(txtSenha.getPassword())))){
				new ControladorSessao().criaSessao(usuario);
				this.dispose();
				new TelaPrincipal(usuario).setVisible(true);
			} else {
				JOptionPane.showMessageDialog(this, "Senha inválida!", "Erro de Login", JOptionPane.OK_OPTION);
			}
		} catch (ControladorExcecao e) {
			ConexaoBD.close();
			JOptionPane.showMessageDialog(this, e.getMessage(), "Erro de Login", JOptionPane.OK_OPTION);
		}
	}//botaoEntrar()

	public void actionPerformed(ActionEvent e) {

		String comando = e.getActionCommand();

		if (comando.equals(btnEntrar.getActionCommand())) {
			botaoEntrar();
		} else if (comando.equals(btnCancelar.getActionCommand())) {
			ConexaoBD.close();
			System.exit(0);
		}

	}//actionPerformed()

}//TelaLogin.class
